package pub.dsb.example.netty.time;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * <p>
 * I/O 数据处理器
 * </p>
 *
 * @author Yi
 * @version V1.0.0
 * @date 2020/12/28 11:08
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify By: {修改人} 2020/12/28 11:08
 * @modify reason: {方法名}:{原因}
 * ...
 * @since V1.0.0
 */
public class TimeServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception { // [1]
//        final ByteBuf time = ctx.alloc().buffer(4); // [2]
//        time.writeInt(89); //ASCII 10进制，对应 Y
//        time.writeInt(105); //ASCII 10进制，对应 i
//        final ChannelFuture f = ctx.writeAndFlush(time); // [3]
//        f.addListener(new ChannelFutureListener() {
//            @Override
//            public void operationComplete(ChannelFuture future) {
//                assert f == future;
//                ctx.close();
//            }
//        }); // [4]
        final ByteBuf time = ctx.alloc().buffer(4); // (2)
        time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L));

        final ChannelFuture f = ctx.writeAndFlush(time); // (3)
        f.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                assert f == future;
                ctx.close();
            }
        }); // (4)
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // super.exceptionCaught(ctx, cause);
        // 当异常发生的时候关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}
